﻿@page "/product/{id:int}"

@inject IProductService _productService
@inject ICartService _cartService

@if (product == null)
{
    <span>@message</span>
}
else
{
    <div class="media">
        <div class="media-img-wrapper mr-2">
            <img class="media-img" src="@product.ImageUrl" alt="@product.Title" />
        </div>
        <div class="media-body">
            <h2 class="mb-0">@product.Title</h2>
            <p>@product.Description</p>

            @if (product.Variants != null && product.Variants.Count > 1)
            {
                <div class="mb-3">
                    <select class="form-select" @bind="currentTypeId">
                        @foreach (var variant in product.Variants)
                        {
                            <option value="@variant.ProductTypeId">@variant.ProductType.Name</option>
                        }
                    </select>

                </div>
            }

            @if (GetSelectedVariant() != null)
            {
                @if (GetSelectedVariant().OriginalPrice > GetSelectedVariant().Price)
                {
                    <h6 class="text-muted original-price">
                        $@GetSelectedVariant().OriginalPrice
                    </h6>
                }
                <h4 class="price">
                    $@GetSelectedVariant().Price
                </h4>
            }
            <button class="btn btn-primary" @onclick="AddToCart">
                <i class="oi oi-cart"></i>&nbsp;&nbsp;&nbsp;Add To Cart
            </button>

        </div>
    </div>
}



@code {
    private Product? product = null;
    private string message = string.Empty;
    private int currentTypeId = 1;


    [Parameter]
    public int Id { get; set; }

    protected override async Task OnParametersSetAsync()
    {
        message = "Loading Product...";
        var result = await _productService.GetProduct(Id);
        if (!result.Success)
        {
            message = result.Message;
        }
        else
        {
            product = result.Data;
            if (product.Variants.Count > 0)
            {
                currentTypeId = product.Variants[0].ProductTypeId;
            }
        }
    }

    private ProductVariant GetSelectedVariant()
    {
        var variant = product.Variants.FirstOrDefault(v => v.ProductTypeId == currentTypeId);
        return variant;
    }

    /// <summary>
    /// 添加购物车
    /// </summary>
    /// <returns></returns>
    private async Task AddToCart()
    {
        var productVariant = GetSelectedVariant();
        var cartItem = new CartItem
        {
            ProductId = productVariant.ProductId,
            ProductTypeId = productVariant.ProductTypeId
        };
        await _cartService.AddToCart(cartItem);
    }

}
